package com.mall.controller;

import com.mall.constant.MessageConstant;
import com.mall.result.Result;
import com.mall.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "文件上传接口")
public class CommonController {

    private final AliOssUtil aliOssUtil;

    @PostMapping("/common/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        /*log.info("文件上传：{}", file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();
        int index = 0;
        if (originalFilename != null) {
            index = originalFilename.lastIndexOf(".");
        }
        String substring = null;
        if (originalFilename != null) {
            substring = originalFilename.substring(index);
        }
        String newFilename = UUID.randomUUID() + substring;
        try {
            file.transferTo(new File("D:\\VueProject\\perfect-mall\\src\\assets\\image" + newFilename));
            log.info("文件上传成功：{}", newFilename);
            return Result.success(newFilename);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }*/


        log.info("文件上传：{}", file.getOriginalFilename());
        try {
            String url = aliOssUtil.upload(file);
            log.info("文件上传成功：{}", url);
            return Result.success(url);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
    
}
